package cn.iocoder.yudao.module.wine.service.supplyfavorite;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.MPJLambdaWrapperX;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.dict.dto.DictDataRespDTO;
import cn.iocoder.yudao.module.wine.dal.dataobject.businesscredit.BusinessCreditDO;
import cn.iocoder.yudao.module.wine.dal.dataobject.businessuser.BusinessUserDO;
import cn.iocoder.yudao.module.wine.dal.dataobject.membertype.MemberTypeDO;
import cn.iocoder.yudao.module.wine.dal.dataobject.supplyinfo.SupplyInfoDO;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.wine.controller.app.supplyfavorite.vo.*;
import cn.iocoder.yudao.module.wine.dal.dataobject.supplyfavorite.SupplyFavoriteDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.wine.dal.mysql.supplyfavorite.SupplyFavoriteMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.wine.enums.ErrorCodeConstants.*;

/**
 * 供求信息收藏 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class SupplyFavoriteServiceImpl implements SupplyFavoriteService {

    @Resource
    private SupplyFavoriteMapper supplyFavoriteMapper;

    @Resource
    private DictDataApi dataApi;

    @Override
    public Long createSupplyFavorite(AppSupplyFavoriteSaveReqVO createReqVO) {
        // 插入
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        SupplyFavoriteDO supplyFavorite = BeanUtils.toBean(createReqVO, SupplyFavoriteDO.class);
        Long count = supplyFavoriteMapper.selectCount(new LambdaQueryWrapperX<SupplyFavoriteDO>()
                .eq(SupplyFavoriteDO::getSupplyInfoId, createReqVO.getSupplyInfoId())
                .eq(SupplyFavoriteDO::getUserId, loginUserId));
        if (count > 0){
            throw exception(DUPLICATE_COLLECTION);
        }
        supplyFavorite.setUserId(loginUserId);
        supplyFavoriteMapper.insert(supplyFavorite);
        // 返回
        return supplyFavorite.getId();
    }

    @Override
    public void deleteSupplyFavorite(Long id) {
        // 校验存在
        validateSupplyFavoriteExists(id);
        // 删除
        supplyFavoriteMapper.deleteById(id);
    }

    private void validateSupplyFavoriteExists(Long id) {
        if (supplyFavoriteMapper.selectById(id) == null) {
            throw exception(INFO_NOT_EXISTS);
        }
    }

    @Override
    public SupplyFavoriteDO getSupplyFavorite(Long id) {
        return supplyFavoriteMapper.selectById(id);
    }

    @Override
    public PageResult<SupplyFavoriteDO> getSupplyFavoritePage(AppSupplyFavoritePageReqVO pageReqVO) {
        return supplyFavoriteMapper.selectPage(pageReqVO);
    }

    @Override
    public List<AppSupplyFavoriteRespVO> getSupplyFavoriteList(AppSupplyFavoritePageReqVO listReqVO) {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        List<AppSupplyFavoriteRespVO> appSupplyFavoriteRespVOS = supplyFavoriteMapper.selectJoinList(AppSupplyFavoriteRespVO.class, new MPJLambdaWrapperX<SupplyFavoriteDO>()
                .eqIfPresent(SupplyFavoriteDO::getUserId, loginUserId)
                .leftJoin(SupplyInfoDO.class, SupplyInfoDO::getId, SupplyFavoriteDO::getSupplyInfoId)
                .leftJoin(MemberUserDO.class, MemberUserDO::getId, SupplyInfoDO::getUserId)
                .leftJoin(BusinessUserDO.class, BusinessUserDO::getUserId, SupplyInfoDO::getUserId)
                .leftJoin(BusinessCreditDO.class, BusinessCreditDO::getId, BusinessUserDO::getCreditId)
                .leftJoin(MemberTypeDO.class, MemberTypeDO::getId, BusinessUserDO::getMemberTypeId)
                .eqIfExists(SupplyInfoDO::getSupplyTypeId, listReqVO.getSupplyTypeId())
                .eqIfExists(SupplyInfoDO::getTradeStatus, listReqVO.getTradeStatus())
                .eqIfExists(SupplyInfoDO::getInfoType, listReqVO.getInfoType())
                .eqIfExists(SupplyInfoDO::getIsDuty, listReqVO.getIsDuty())
                .selectAll(SupplyInfoDO.class)
                .selectAs(SupplyFavoriteDO::getCreateTime, AppSupplyFavoriteRespVO::getFavoriteCreateTime)
                .selectAs(MemberUserDO::getNickname, AppSupplyFavoriteRespVO::getNickname)
                .selectAs(MemberUserDO::getAvatar, AppSupplyFavoriteRespVO::getAvatar)
                .selectAs(BusinessUserDO::getIsSelfSupport, AppSupplyFavoriteRespVO::getIsSelfSupport)
                .selectAs(BusinessUserDO::getAreaId, AppSupplyFavoriteRespVO::getUserAreaId)
                .selectAs(BusinessCreditDO::getIcon, AppSupplyFavoriteRespVO::getIcon)
                .selectAs(MemberTypeDO::getIcon, AppSupplyFavoriteRespVO::getMemberTypeIcon)
                .selectAs(MemberTypeDO::getName, AppSupplyFavoriteRespVO::getMemberTypeName)
                .orderByDesc(SupplyFavoriteDO::getCreateTime)
        );
        List<DictDataRespDTO> unit = dataApi.getDictDataList("unit");
        List<DictDataRespDTO> packing = dataApi.getDictDataList("packing");
        List<DictDataRespDTO> capacity = dataApi.getDictDataList("capacity");
        List<DictDataRespDTO> degree = dataApi.getDictDataList("degree");
        List<DictDataRespDTO> year = dataApi.getDictDataList("year");
        List<DictDataRespDTO> odorType = dataApi.getDictDataList("odor_type");
        List<DictDataRespDTO> language = dataApi.getDictDataList("language");
        List<DictDataRespDTO> producingArea = dataApi.getDictDataList("producing_area");
        if (!CollectionUtil.isEmpty(appSupplyFavoriteRespVOS)) {
            List<AppSupplyFavoriteRespVO> collect = appSupplyFavoriteRespVOS.stream().peek(item -> {
                packing.forEach(dict -> {
                    if (dict.getValue().equals(String.valueOf(item.getPacking()))) {
                        item.setPackingName(dict.getLabel());
                    }
                });
                capacity.forEach(dict -> {
                    if (dict.getValue().equals(String.valueOf(item.getCapacity()))) {
                        item.setCapacityName(dict.getLabel());
                    }
                });
                degree.forEach(dict -> {
                    if (dict.getValue().equals(String.valueOf(item.getDegree()))) {
                        item.setDegreeName(dict.getLabel());
                    }
                });
                year.forEach(dict -> {
                    if (dict.getValue().equals(String.valueOf(item.getShowYear()))) {
                        item.setShowYearName(dict.getLabel());
                    }
                });
                odorType.forEach(dict -> {
                    if (dict.getValue().equals(String.valueOf(item.getFragranceType()))) {
                        item.setFragranceTypeName(dict.getLabel());
                    }
                });
                producingArea.forEach(dict -> {
                    if (dict.getValue().equals(String.valueOf(item.getProductArea()))) {
                        item.setProductAreaName(dict.getLabel());
                    }
                });
                unit.forEach(dict -> {
                    if (dict.getValue().equals(String.valueOf(item.getUnit()))) {
                        item.setUnitName(dict.getLabel());
                    }
                });
            }).collect(Collectors.toList());
            return collect;
        }
        return appSupplyFavoriteRespVOS;

    }

    @Override
    public void deleteSupplyFavoriteBySupplyInfoId(Long supplyInfoId) {
        supplyFavoriteMapper.delete(new MPJLambdaWrapperX<SupplyFavoriteDO>()
                .eq(SupplyFavoriteDO::getSupplyInfoId,supplyInfoId)
                .eq(SupplyFavoriteDO::getUserId,SecurityFrameworkUtils.getLoginUserId()));
    }

    @Override
    public List<AppImageVO> getSupplyFavoriteImage() {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        return supplyFavoriteMapper.selectJoinList(AppImageVO.class, new MPJLambdaWrapperX<SupplyFavoriteDO>()
                .eq(SupplyFavoriteDO::getUserId, loginUserId)
                .leftJoin(SupplyInfoDO.class, SupplyInfoDO::getId, SupplyFavoriteDO::getSupplyInfoId)
                .selectAs(SupplyInfoDO::getImage, AppImageVO::getImage)
                .selectAs(SupplyInfoDO::getImages, AppImageVO::getImages));
    }

}
